package com.honeybees.framework.spring.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.access.BootstrapException;
import org.springframework.stereotype.Component;

/**
 * <dl>
 * <dt><b> Spring支持类，方便在非Spring管理的类中获取到对象 </b></dt>
 * <p>
 * <dd>功能描述</dd>
 * </dl>
 * <p>
 * Copyright (C) All rights reserved.
 * </p>
 *
 * @author 李远明
 * @version 2017-02-27 20:55:28 添加 @Component 注解
 * @since 2015-11-3 19:47:15
 */
@Component
public class BeanFactoryUtil implements BeanFactoryAware {

    private static BeanFactory factory;

    /**
     * {@inheritDoc}
     *
     * @param beanFactory
     * @throws BeansException
     * @author 李远明
     * @version 2015年11月3日 下午7:47:15
     * @see BeanFactoryAware#setBeanFactory(BeanFactory)
     */
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        factory = beanFactory;
    }

//    public static BeanFactory getBeanFactory() {
//        return factory;
//    }

    private static void checkFactory() {
        if (factory == null) { // IllegalStateException
            throw new BootstrapException("Spring未初始化BeanFactoryUtil，请在Spring主配置文件中定义BeanFactoryUtil。");
        }
    }

    /**
     * <DL>
     * <DT><B> 获取指定类型的对象 </B></DT>
     * <p>
     * <DD>&lt;bean class="com.kedao.api.support.springmvc.BeanFactoryUtil" /&gt;</DD>
     * </DL>
     * <p>
     *
     * @param beanName     Bean注册名称
     * @param requiredType 返回对象的类型
     * @return Bean对应的实例
     * @author ijLee89
     * @since 2014-05-07 17:27:32
     */
    public static <T> T getBean(String beanName, Class<T> requiredType) {
        checkFactory();
        return factory.getBean(beanName, requiredType);
    }

    /**
     * 获取指定名称的对象
     *
     * @param name Bean name
     * @return Bean对应的实例
     * @since 2017-05-15 11:02
     */
    public static Object getBean(String name) {
        checkFactory();
        return factory.getBean(name);
    }

    /**
     * 获取指定类型的对象
     *
     * @param requiredType 返回对象的类型
     * @param <T>          类型
     * @return Bean对应的实例
     * @since 2017-05-15 11:04
     */
    public static <T> T getBean(Class<T> requiredType) {
        checkFactory();
        return factory.getBean(requiredType);
    }

}
